// =======================================================
// Runtime/KDTree.cs
// Simple nearest neighbor search
// =======================================================

using UnityEngine;
using System.Collections.Generic;

public class KDTree
{
    Vector3[] pts;

    public KDTree(Vector3[] positions)
    {
        pts = positions;
    }

    public KDTree(List<Vector3> positions)
    {
        pts = positions.ToArray();
    }

    public int FindNearest(Vector3 p)
    {
        int idx = 0;
        float md = float.MaxValue;
        for (int i = 0; i < pts.Length; i++)
        {
            float d = (pts[i] - p).sqrMagnitude;
            if (d < md)
            {
                md = d;
                idx = i;
            }
        }

        return idx;
    }
}